package org.jim.server.command.handler;

import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.ImStatus;
import org.jim.core.cache.redis.JedisTemplate;
import org.jim.core.exception.ImException;
import org.jim.core.packets.AuthReqBody;
import org.jim.core.packets.Command;
import org.jim.core.packets.RespBody;
import org.jim.core.packets.User;
import org.jim.core.packets.UserStatusType;
import org.jim.core.utils.JsonKit;
import org.jim.core.utils.ValidJdbcUtil;
import org.jim.server.JimServerAPI;
import org.jim.server.command.AbstractCmdHandler;
import org.jim.server.protocol.ProtocolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * 版本: [1.0]
 * 功能说明: 鉴权请求消息命令处理器
 * @author : WChao 创建时间: 2017年9月13日 下午1:39:35
 */
public class AuthReqHandler extends AbstractCmdHandler{
	
	/**
	 * 日志
	 */
	private static Logger log = LoggerFactory.getLogger(AuthReqHandler.class);
	
	@Override
	public ImPacket handler(ImPacket packet, ImChannelContext channelContext) throws ImException
	{
		if (packet.getBody() == null) {
			RespBody respBody = new RespBody(Command.COMMAND_AUTH_RESP,ImStatus.C10010);
			return ProtocolManager.Converter.respPacket(respBody, channelContext);
		}
		AuthReqBody authReqBody = JsonKit.toBean(packet.getBody(), AuthReqBody.class);
		String appid = authReqBody.getAppId();
		String appkey  = authReqBody.getAppKey();
		ValidJdbcUtil validJdbcUtil = new ValidJdbcUtil();
		if (validJdbcUtil.validation(appid, appkey)) {
			User.Builder builder = User.newBuilder().userId(authReqBody.getUserId());
			builder.status(UserStatusType.ONLINE.getStatus());
			User user = builder.build();
			JimServerAPI.bindUser(channelContext, user);
			authReqBody.setCmd(4);
			RespBody respBody = new RespBody(Command.COMMAND_AUTH_RESP,ImStatus.C10009);
			return ProtocolManager.Converter.respPacket(respBody.setLocalId(authReqBody.getLocalId()), channelContext);
		}else {
			RespBody respBody = new RespBody(Command.COMMAND_AUTH_RESP,ImStatus.C10010);
			return ProtocolManager.Converter.respPacket(respBody.setLocalId(authReqBody.getLocalId()), channelContext);
		}
		
	}

	@Override
	public Command command() {
		return Command.COMMAND_AUTH_REQ;
	}
}
